package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 处理热点评论
     *
     * @param apComment 评论信息
     */
    @Async("taskExecutor")
    public void hotCommentExecutor(ApComment apComment) {
        log.info("异步计算热点评论开始=====>");
        //获取当前文章的所有热点评论
        Query query = Query.query(Criteria
                .where("articleId").is(apComment.getArticleId())
                .and("flag").is((short) 1))
                .with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        //如果当前热点评论集合为空，或者当前热点评论小于5条，则把当前评论直接变成热点评论
        if (CollectionUtils.isEmpty(apComments) || apComments.size() < 5) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        //如果热点评论够5条则将当前评论的点赞数与已有热点评论数对比，判断能否升级为热点评论
        ApComment oldApComment = apComments.get(apComments.size() - 1);
        if (apComment.getLikes() >= oldApComment.getLikes()) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            oldApComment.setFlag((short) 0);
            mongoTemplate.save(oldApComment);
        }
        log.info("异步计算热点评论结束=====>");
    }
}